package com.ruoyi.project.lesson.course.controller;

import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.lesson.course.domain.BatchAddForm;
import com.ruoyi.project.lesson.course.domain.CourseVod;
import com.ruoyi.project.lesson.course.domain.LessonCourse;
import com.ruoyi.project.lesson.course.service.ILessonCourseService;
import com.ruoyi.project.lesson.lesson.service.ILessonService;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 课程章节Controller
 *
 * @author shixiangwen
 * @date 2020-12-07
 */
@Controller
@RequestMapping("/lesson/course")
public class LessonCourseController extends BaseController {

    protected static org.apache.commons.logging.Log logger = LogFactory.getLog(LessonCourseController.class);

    private String prefix = "lesson/course";

    @Autowired
    private ILessonCourseService lessonCourseService;

    @Autowired
    RuoYiConfig ruoYiConfig;

    @Autowired
    private ILessonService lessonService;

    @RequiresPermissions("lesson:course:view")
    @GetMapping("/{lessonId}")
    public String course(@PathVariable("lessonId") Long lessonId, ModelMap mmap) {

        mmap.put("lesson", lessonService.selectLessonById(lessonId));

        return prefix + "/course";
    }

    /**
     * 查询课程章节列表
     */
    @RequiresPermissions("lesson:course:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(LessonCourse lessonCourse) {
        startPage();
        List<LessonCourse> list = lessonCourseService.selectLessonCourseList(lessonCourse);
        return getDataTable(list);
    }

    /**
     * 导出课程章节列表
     */
    @RequiresPermissions("lesson:course:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(LessonCourse lessonCourse) {
        List<LessonCourse> list = lessonCourseService.selectLessonCourseList(lessonCourse);
        ExcelUtil<LessonCourse> util = new ExcelUtil<LessonCourse>(LessonCourse.class);
        return util.exportExcel(list, "course");
    }

    /**
     * 新增课程章节
     */
    @GetMapping("/add/{lessonId}")
    public String add(@PathVariable("lessonId") Long lessonId, ModelMap mmap) {
        mmap.put("lessonId", lessonId);
        mmap.put("lesson", lessonService.selectLessonById(lessonId));
        mmap.put("sort", lessonCourseService.getMaxSort(lessonId));
        return prefix + "/add";
    }

    @GetMapping("/batchadd/{lessonId}")
    public String batchadd(@PathVariable("lessonId") Long lessonId, ModelMap mmap) {
        mmap.put("lessonId", lessonId);
        mmap.put("lesson", lessonService.selectLessonById(lessonId));
        return prefix + "/batchadd";
    }

    /**
     * 新增保存课程章节
     */
    @RequiresPermissions("lesson:course:add")
    @Log(title = "课程章节", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(LessonCourse lessonCourse) {
        return toAjax(lessonCourseService.insertLessonCourse(lessonCourse));
    }

    @RequiresPermissions("lesson:course:add")
    @Log(title = "课程章节", businessType = BusinessType.INSERT)
    @PostMapping("/batchadd")
    @ResponseBody
    public AjaxResult batchaddSave(@RequestBody BatchAddForm form) {
        int sort = lessonCourseService.getMaxSort(form.getLessonId());
        for (CourseVod vod : form.getVods()) {
            LessonCourse lessonCourse = new LessonCourse();
            lessonCourse.setCreatedTime(DateUtils.getNowDate());
            lessonCourse.setLessonId(form.getLessonId());
            lessonCourse.setName(vod.getCourseName());
            lessonCourse.setResSize(vod.getSize());
            lessonCourse.setResType(vod.getResType());
            lessonCourse.setVodId(vod.getVodId());
            lessonCourse.setSort((long) sort++);
            lessonCourse.setCreateBy(ShiroUtils.getLoginName());
            lessonCourseService.insertLessonCourse(lessonCourse);
        }
        return toAjax(true);
    }


    /**
     * 修改课程章节
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        LessonCourse lessonCourse = lessonCourseService.selectLessonCourseById(id);
        mmap.put("lessonCourse", lessonCourse);
        return prefix + "/edit";
    }

    /**
     * 修改保存课程章节
     */
    @RequiresPermissions("lesson:course:edit")
    @Log(title = "课程章节", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(LessonCourse lessonCourse) {
        return toAjax(lessonCourseService.updateLessonCourse(lessonCourse));
    }

    /**
     * 删除课程章节
     */
    @RequiresPermissions("lesson:course:remove")
    @Log(title = "课程章节", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(lessonCourseService.deleteLessonCourseByIds(ids));
    }


    private static String getMediaType(String contentType) {
        String[] datas = contentType.split("/");
        return datas[0];
    }

    @PostMapping("/uploadMedia")
    @ResponseBody
    public AjaxResult uploadMedia(MultipartFile file, String courseName) throws Exception {
        try {

            String name = MultipartFileUtil.getRandName(file);

            String filepath = RuoYiConfig.getUploadPath() + File.separator + name;
            File desc = new File(filepath);

            if (!desc.exists()) {
                file.transferTo(desc);
            }

            if (StringUtils.isEmpty(courseName)) {
                courseName = file.getOriginalFilename().replaceAll(".mp4", "").replaceAll(".mp3", "");
            }

            String type = getMediaType(file.getContentType());
            String vodId = RuoYiConfig.isDev() ? "test" : MediaUtil.upload(type, courseName, filepath, 1);

            AjaxResult ajax = AjaxResult.success();
            ajax.put("vodId", vodId);
            ajax.put("courseName", courseName);
            ajax.put("resType", StringUtils.equalsIgnoreCase(type, "audio") ? 2 : 1);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/batchUploadMedia")
    @ResponseBody
    public AjaxResult batchUploadMedia(HttpServletRequest request) throws Exception {
        try {
            List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("files");
            AjaxResult ajax = AjaxResult.success();
            List<Map<String, Object>> vods = new ArrayList<>();
            for (MultipartFile file : files) {

                String name = MultipartFileUtil.getRandName(file);
                String courseName = file.getOriginalFilename().replaceAll(".mp4", "").replaceAll(".mp3", "");

                String filepath = RuoYiConfig.getUploadPath() + File.separator + name;
                File desc = new File(filepath);

                if (!desc.exists()) {
                    file.transferTo(desc);
                }
                String type = getMediaType(file.getContentType());

                String vodId = RuoYiConfig.isDev() ? "test" : MediaUtil.upload(type, courseName, filepath, 1);

                Map<String, Object> vod = new HashMap<>();
                vod.put("vodId", vodId);
                vod.put("courseName", courseName);
                vod.put("size", file.getSize());
                vod.put("resType", StringUtils.equalsIgnoreCase(type, "audio") ? 2 : 1);
                vods.add(vod);
            }
            ajax.put("vods", vods);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    public static void main(String[] args) {
        System.out.println(getMediaType("video/mp4"));
        System.out.println(getMediaType("audio/mpeg"));
    }
}
